package com.mysteel.ware.service.impl;

import com.mysteel.common.constant.WareConstant;
import com.mysteel.ware.entity.PurchaseDetailEntity;
import com.mysteel.ware.service.PurchaseDetailService;
import com.mysteel.ware.service.WareSkuService;
import com.mysteel.ware.vo.MergeVo;
import com.mysteel.ware.vo.PurchaseDoneItemVo;
import com.mysteel.ware.vo.PurchaseDoneVo;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysteel.common.utils.PageUtils;
import com.mysteel.common.utils.Query;

import com.mysteel.ware.dao.PurchaseDao;
import com.mysteel.ware.entity.PurchaseEntity;
import com.mysteel.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        List<Long> items = mergeVo.getItems();
        // 检查当前采购需求状态，只有新建或已分配的能进行合并
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(items);
        List<Long> mergeIds = purchaseDetailEntities.stream()
                .filter(p -> p.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode()) || p.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()))
                .map(PurchaseDetailEntity::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(mergeIds)){
            return;
        }
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }else {
            // 更新时间
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            this.updateById(purchaseEntity);
        }

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = mergeIds.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);
    }

    @Override
    public void receivedList(List<Long> ids) {
        // 确认当前采购单为新建或已分配状态
        List<PurchaseEntity> collect = ids.stream()
                .map(id -> {
                    PurchaseEntity byId = this.getById(id);
                    return byId;
                })
                .filter(item -> item.getStatus().equals(WareConstant.PurchaseStatusEnum.CREATED.getCode()) || item.getStatus().equals(WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()))
                .peek(purchaseEntity -> {
                    purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
                    purchaseEntity.setUpdateTime(new Date());
                })
                .collect(Collectors.toList());
        // 改变采购单的状态
        this.updateBatchById(collect);

        // 修改采购项的状态
        collect.forEach(item -> {
            // 查出当前采购单的所有采购项信息
            List<PurchaseDetailEntity> purchaseDetailList = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> updateDetailList = purchaseDetailList.stream()
                    .map(detail -> {
                        PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                        detailEntity.setId(detail.getId());
                        detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                        return detailEntity;
                    }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(updateDetailList);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 改变采购项状态
        Integer status = WareConstant.PurchaseStatusEnum.FINISHED.getCode();
        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> updateDetails = new ArrayList<>();
        for (PurchaseDoneItemVo item : items){
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus().equals(WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode())){
                status = WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode();
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.PURCHASE_FAILED.getCode());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode());
                // 采购成功的采购项入库
                PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updateDetails.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updateDetails);
        // 改变采购单状态
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(purchaseDoneVo.getId());
        entity.setStatus(status);
        entity.setUpdateTime(new Date());
        this.updateById(entity);
    }

    @Override
    public PageUtils queryPageOnCondition(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper -> {
                wrapper.eq("id",key).or().like("assignee_name",key).or().eq("phone",key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){
            queryWrapper.eq("status",status);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

}